const amapKey = "de8f014adc7c59857453b0bc8b7bc2a8";

Page({
    data: {
        orderType: 1,
        pickUpTime: "",
        sendTime: "",
        latitude: 39.908723,  // 默认北京天安门
        longitude: 116.397477,
        departureLocation: "点击选择出发地",
        departureLatitude: null,
        departureLongitude: null,
        arrivalLocation: "点击选择目的地",
        arrivalLatitude: null,
        arrivalLongitude: null,
        markers: [],
        children: [],
        childNames: [],
        selectedChild: '',
        selectedChildId: '',
        selectedDateStart: '',
        selectedDateEnd: '',
        selectedDateSingle: '',
        totalPrice: 0,
        orderSituation: 0,
        remarks: "",
        agreementChecked: false, // 是否勾选协议
    },

    onLoad() {
        this.fetchChildren();
        this.getUserLocation();
    },
    // 监听协议勾选状态
    toggleAgreement(e) {
        this.setData({
            agreementChecked: e.detail.value.length > 0
        });
    },

// 打开协议页面
viewAgreement() {
    wx.navigateTo({
        url: "/pages/index/agreement/agreement"
    });
},
    // 获取用户当前位置
    getUserLocation() {
        wx.getLocation({
            type: 'gcj02',
            success: (res) => {
                console.log("✅ 当前定位：", res);
                this.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
            },
            fail: (err) => {
                console.error("❌ 获取定位失败：", err);
                wx.showToast({ title: "请开启定位权限", icon: "none" });
            }
        });
    },

    // 选择出发地
    chooseDepartureLocation() {
        this.chooseLocation("departure");
    },

    // 选择目的地
    chooseArrivalLocation() {
        this.chooseLocation("arrival");
    },

    // 统一处理出发地 & 目的地选择
    chooseLocation(type) {
        wx.chooseLocation({
            success: (res) => {
                console.log(`✅ 选择${type === "departure" ? "出发地" : "目的地"}：`, res);
                this.getAddressFromCoordinates(res.latitude, res.longitude)
                    .then((address) => {
                        let newMarkers = [...this.data.markers];
                        let markerId = type === "departure" ? 1 : 2;
                        let markerIndex = newMarkers.findIndex(m => m.id === markerId);

                        let newMarker = {
                            id: markerId,
                            latitude: res.latitude,
                            longitude: res.longitude,
                            iconPath: "/images/marker.png",
                            width: 30,
                            height: 30
                        };

                        if (markerIndex >= 0) {
                            newMarkers[markerIndex] = newMarker;
                        } else {
                            newMarkers.push(newMarker);
                        }

                        this.setData({
                            [`${type}Location`]: address || res.name || "未知地址",
                            [`${type}Latitude`]: res.latitude,
                            [`${type}Longitude`]: res.longitude,
                            markers: newMarkers
                        });
                    })
                    .catch(() => {
                        this.setData({
                            [`${type}Location`]: res.name || "未知地址",
                            [`${type}Latitude`]: res.latitude,
                            [`${type}Longitude`]: res.longitude
                        });
                    });
            },
            fail: (err) => {
                console.error(`❌ 选择${type === "departure" ? "出发地" : "目的地"}失败：`, err);
                wx.showToast({ title: `选择${type === "departure" ? "出发地" : "目的地"}失败`, icon: "none" });
            }
        });
    },

    // 使用高德 API 将经纬度转换为详细地址
    getAddressFromCoordinates(lat, lng) {
        return new Promise((resolve) => {
            wx.request({
                url: `https://restapi.amap.com/v3/geocode/regeo`,
                method: "GET",
                data: { key: amapKey, location: `${lng},${lat}` },
                success: (res) => {
                    console.log("📌 逆地理编码返回：", res);
                    resolve(res.data.status === "1" ? res.data.regeocode.formatted_address : "未知地址");
                },
                fail: (err) => {
                    console.error("❌ 逆地理编码请求失败：", err);
                    resolve("未知地址");
                }
            });
        });
    }
    ,

    // 获取绑定的孩子列表
    fetchChildren() {
      console.log("📌 正在请求孩子列表...");
      const parentId = wx.getStorageSync("parentId");
      const token = wx.getStorageSync("token");
  
      if (!parentId) {
        wx.showToast({ title: "未找到家长ID，请重新登录", icon: "none" });
        return;
      }
  
      wx.request({
        url: "http://localhost:8081/parent/child/list",
        method: "GET",
        header: {
          "Authorization": `Bearer ${token}`,
          "parentId": parentId
        },
        success: (res) => {
          console.log("📌 获取孩子信息:", res);
          if (res.statusCode === 200 && Array.isArray(res.data)) {
            const childNames = res.data.map(child => child.name);
            this.setData({ children: res.data, childNames });
          } else {
            wx.showToast({ title: "未找到绑定的孩子", icon: "none" });
          }
        },
        fail: (err) => {
          console.error("❌ 获取孩子信息失败:", err);
          wx.showToast({ title: "服务器未连接", icon: "none" });
        }
      });
    },
  
    // 选择孩子
    selectChild(e) {
      const index = e.detail.value;
      const selectedChild = this.data.children[index];
      this.setData({
        selectedChild: selectedChild.name,
        selectedChildId: selectedChild.childId
      });
    },
  
    chooseStartDate(e) {
      this.setData({ selectedDateStart: e.detail.value });
      this.calculatePrice();
    },
  
    chooseEndDate(e) {
      this.setData({ selectedDateEnd: e.detail.value });
      this.calculatePrice();
    },
  
    chooseSingleDate(e) {
      this.setData({ selectedDateSingle: e.detail.value });
      this.calculatePrice();
    },
  
    calculatePrice() {
        if (this.data.orderSituation === 0) {
            // 单次订单计算价格
            this.setData({ totalPrice: this.data.orderType === 0 ? 10 : 15 });
        } else if (this.data.orderSituation === 1) {
            // 计算长期订单的天数
            if (this.data.selectedDateStart && this.data.selectedDateEnd) {
                let days = this.getDaysBetween(new Date(this.data.selectedDateStart), new Date(this.data.selectedDateEnd));
                let pricePerDay = this.data.orderType === 0 ? 10 : 15;
                this.setData({ totalPrice: days * pricePerDay });
            }
        }
    },
    
    // 计算两个日期之间的天数
    getDaysBetween(date1, date2) {
        const diff = Math.abs(date2 - date1);
        return Math.ceil(diff / (1000 * 60 * 60 * 24)) + 1; // 包括最后一天
    },
  
    submitOrder() {
        if (!this.data.agreementChecked) {
            wx.showToast({ title: "请先阅读并同意协议", icon: "none" });
            return;
        }
        if (!this.data.selectedChildId) {
            wx.showToast({ title: "请选择接送对象", icon: "none" });
            return;
        }
        if (!this.data.pickUpTime) {
            wx.showToast({ title: "请选择接时间", icon: "none" });
            return;
        }
        if (this.data.orderType === 1 && !this.data.sendTime) {
            wx.showToast({ title: "请选择送时间", icon: "none" });
            return;
        }
        if (!this.data.departureLatitude || !this.data.arrivalLatitude) {
            wx.showToast({ title: "请正确选择出发地和目的地", icon: "none" });
            return;
        }
    
        let orderDateList = this.data.orderSituation === 0
            ? [this.data.selectedDateSingle]
            : this.generateDateList(this.data.selectedDateStart, this.data.selectedDateEnd);
    
        const orderData = {
            parentId: wx.getStorageSync("parentId"),
            childId: this.data.selectedChildId,
            departureLongitudeLatitude: `${this.data.departureLatitude},${this.data.departureLongitude}`,
            arriveLongitudeLatitude: `${this.data.arrivalLatitude},${this.data.arrivalLongitude}`,
            pickUpTime: `${this.data.pickUpTime}:00`,
            sendTime: this.data.orderType === 1 ? `${this.data.sendTime}:00` : null,
            orderType: this.data.orderType,
            orderSituation: this.data.orderSituation,
            orderDateList: JSON.stringify(orderDateList),
            totalPrice: this.data.totalPrice,
            payAmount: this.data.totalPrice,
            remarks: this.data.remarks || "无"
        };
    
        console.log("📌 发送订单数据:", orderData);
    
        wx.request({
            url: "http://localhost:8081/orders/submit",
            method: "POST",
            data: orderData,
            success: (res) => {
                if (res.data.code === 0) {
                    const bookingOrderId = res.data.data?.bookingOrderId;
                    if (!bookingOrderId) {
                        wx.showModal({ title: "下单失败", content: "未能获取订单 ID，请稍后重试" });
                        return;
                    }
    
                    this.setData({ bookingOrderId });
    
                    // ✅ 订单提交成功后 **先提示成功**，然后**跳转支付页面**
                    wx.showToast({
                        title: "订单提交成功",
                        icon: "success",
                        duration: 1500,
                        success: () => {
                            console.log("📌 跳转到支付页面:", bookingOrderId);
                            wx.navigateTo({
                                url: `/pages/index/payment/payment?orderId=${bookingOrderId}&amount=${this.data.totalPrice}`
                            });
                        }
                    });
                } else {
                    wx.showModal({ title: "下单失败", content: res.data.message || "订单提交失败，请稍后重试" });
                }
            },
            fail: () => {
                wx.showToast({ title: "网络错误，请稍后重试", icon: "none" });
            }
        });
    },
    
    // 生成长期订单的日期列表
    generateDateList(startDate, endDate) {
        let dates = [];
        let start = new Date(startDate);
        let end = new Date(endDate);
        for (let d = start; d <= end; d.setDate(d.getDate() + 1)) {
            dates.push(d.toISOString().split('T')[0]);
        }
        return dates;
    },
    
    
  
    switchOrderType(e) {
        const selectedType = Number(e.currentTarget.dataset.type);
        if (this.data.orderType !== selectedType) {
            this.setData({ orderType: selectedType });
        }
    },

    // 选择接时间
    onPickUpTimeChange(e) {
        console.log("✅ 选择的接时间:", e.detail.value);
        this.setData({ pickUpTime: e.detail.value || "08:00" }); // 默认08:00
    },
    onDepartureInput(e) {
        this.setData({ departureLocation: e.detail.value });
    },
    
    onArrivalInput(e) {
        this.setData({ arrivalLocation: e.detail.value });
    },
    selectOrderSituation(e) {
        const situation = parseInt(e.detail.value); // 转换为整数
        this.setData({ orderSituation: situation });
    },

    onRemarksInput(e) {
        this.setData({ remarks: e.detail.value });
    },
    
// 选择送时间
onSendTimeChange(e) {
    this.setData({
        sendTime: e.detail.value
    });
    console.log("✅ 选择的送时间:", e.detail.value);
},
// 选择单次订单的日期
chooseSingleDate(e) {
    this.setData({ selectedDateSingle: e.detail.value });
    this.calculatePrice();
},

// 选择长期订单的起始日期
chooseStartDate(e) {
    this.setData({ selectedDateStart: e.detail.value });
    this.calculatePrice();
},

// 选择长期订单的结束日期
chooseEndDate(e) {
    this.setData({ selectedDateEnd: e.detail.value });
    this.calculatePrice();
}

  });
  